#!/usr/bin/perl

use JSON;
$HOME_DIR = "/home/one-tenth";
$HOME_DIR = $ENV{'CHOPSET_HOME'} if($ENV{'CHOPSET_HOME'} ne '');

require "$HOME_DIR/config.ph";

@nodes = &getNodeList();

foreach $node (@nodes){
	$jobs = "";
	if(open(NODE, "<$NODE_STATUS_DIR/$node")){
		flock(NODE, 1);
		seek(NODE, 0, 0);
		while(<NODE>){
			s/\r?\n$//;
			$jobs .= $_. " ";
		}
		flock(NODE, 8);
		close(NODE);
	}
	$jobs{$node} = $jobs;
}
if(open(FILE, "<$DESTROYED_NODES_FILE")){
	flock(FILE, 1);
	seek(FILE, 0, 0);
	while(<FILE>){
		s/\r?\n$//;
		$destoryedNode{$_} = 1;
	}
	flock(FILE, 8);
	close(FILE);
}

print "all nodes are:\n";
foreach $node (@nodes){
	print $node, " ";
	if(defined($destoryedNode{$node})){
		print "destroyed ";
	}else{
		print "alive ";
	}
	print $jobs{$node};
	print "\n";
}

print "all jobs are:\n";
$jsonObj = {};
undef(@results);
if(opendir(DIR, $WORK_DIR)){
	while(defined($jobdir = readdir(DIR))){
		next if($jobdir =~ m/^\./);
		$resultFile = "$WORK_DIR/$jobdir/result";
		$r = "\"$jobdir\":{";
		if(open(RESULT, "<$resultFile")){
			$result = <RESULT>;
			$result =~ s/\r?\n$//;
			$value = join('', <RESULT>);
			$jsonObj->{$jobdir}->{"Result"} = $result;
			$jsonObj->{$jobdir}->{"Value"} = $value;
			close(RESULT);
		}else{
			$jsonObj->{$jobdir}->{"Result"} = "not solved.";
		}
		push(@results, $r);
	}
}
print to_json($jsonObj);
